var express = require('express');
var router = express.Router();
const { UserModel } = require('../db/index');
const FlashSaleActivityModel = require('../db/bkc/FlashSaleActivity');
const GroupBuyActivityModel = require('../db/bkc/GroupBuyActivity');

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

// 登录接口
router.post('/login', async function (req, res) {
  const { userName, passWord } = req.body;
  try {
    const user = await UserModel.findOne({ userName, passWord });
    if (!user) {
      return res.status(401).json({ code: 401, message: '用户名或密码错误' });
    }

    // 返回用户基本信息
    res.json({
      code: 200,
      message: '登录成功',
      data: {
        userName: user.userName,
        passWord: user.passWord,
      }
    });
  } catch (error) {
    res.status(500).json({ code: 500, message: '服务器错误', error: error.message });
  }
});

// 用户注册接口
router.post('/register', async function (req, res) {
  const { username, phone, password } = req.body;
  if (!username || !phone || !password) {
    return res.status(400).json({ code: 400, message: '用户名、手机号和密码不能为空' });
  }
  try {
    // 检查手机号或用户名是否已注册
    const exist = await YonghuUserModel.findOne({ $or: [{ phone }, { userName: username }] });
    if (exist) {
      return res.status(409).json({ code: 409, message: '手机号或用户名已注册' });
    }
    // 创建新用户
    const user = await YonghuUserModel.create({ 
      id: Date.now().toString(), // 生成唯一ID
      userName: username, 
      nickname: username, // 默认昵称为用户名
      phone, 
      email: `${username}@example.com`, // 默认邮箱
      passWord: password 
    });
    res.json({ code: 200, message: '注册成功', data: { id: user.id, userName: user.userName, phone: user.phone } });
  } catch (error) {
    res.status(500).json({ code: 500, message: '服务器错误', error: error.message });
  }
});

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

// 秒杀活动列表（分页、筛选、数据库联动）
router.get('/flash-sale/activities', async (req, res) => {
  try {
    const { page = 1, pageSize = 10, name = '', status = '', online = '', start = '', end = '' } = req.query;
    const skip = (parseInt(page) - 1) * parseInt(pageSize);
    const query = {};
    if (name) query.name = { $regex: name, $options: 'i' };
    if (status) query.status = status;
    if (online) query.online = online;
    // 时间筛选（假设time为'2021-03-02 ~ 2021-03-12'字符串）
    if (start && end) query.time = { $regex: `${start} ~ ${end}` };
    const total = await FlashSaleActivityModel.countDocuments(query);
    const list = await FlashSaleActivityModel.find(query).skip(skip).limit(parseInt(pageSize)).sort({ _id: -1 });
    res.json({ code: 200, data: { list, total } });
  } catch (error) {
    res.status(500).json({ code: 500, message: '查询失败', error: error.message });
  }
});
// 新建活动
router.post('/flash-sale/activities', async (req, res) => {
  try {
    const doc = await FlashSaleActivityModel.create(req.body);
    res.json({ code: 200, message: '新建成功', data: doc });
  } catch (error) {
    res.status(500).json({ code: 500, message: '新建失败', error: error.message });
  }
});
// 编辑活动
router.put('/flash-sale/activities/:id', async (req, res) => {
  try {
    const doc = await FlashSaleActivityModel.findByIdAndUpdate(req.params.id, req.body, { new: true });
    res.json({ code: 200, message: '编辑成功', data: doc });
  } catch (error) {
    res.status(500).json({ code: 500, message: '编辑失败', error: error.message });
  }
});
// 删除活动
router.delete('/flash-sale/activities/:id', async (req, res) => {
  try {
    await FlashSaleActivityModel.findByIdAndDelete(req.params.id);
    res.json({ code: 200, message: '删除成功' });
  } catch (error) {
    res.status(500).json({ code: 500, message: '删除失败', error: error.message });
  }
});
// 下线活动
router.post('/flash-sale/activities/:id/offline', async (req, res) => {
  try {
    const doc = await FlashSaleActivityModel.findByIdAndUpdate(req.params.id, { online: '下线' }, { new: true });
    res.json({ code: 200, message: '下线成功', data: doc });
  } catch (error) {
    res.status(500).json({ code: 500, message: '下线失败', error: error.message });
  }
});

// 拼团活动列表（分页、筛选、数据库联动）
router.get('/group-buy/activities', async (req, res) => {
  try {
    const { page = 1, pageSize = 10, name = '', status = '', online = '', start = '', end = '' } = req.query;
    const skip = (parseInt(page) - 1) * parseInt(pageSize);
    const query = {};
    if (name) query.name = { $regex: name, $options: 'i' };
    if (status) query.status = status;
    if (online) query.online = online;
    if (start && end) query.time = { $regex: `${start} ~ ${end}` };
    const total = await GroupBuyActivityModel.countDocuments(query);
    const list = await GroupBuyActivityModel.find(query).skip(skip).limit(parseInt(pageSize)).sort({ _id: -1 });
    res.json({ code: 200, data: { list, total } });
  } catch (error) {
    res.status(500).json({ code: 500, message: '查询失败', error: error.message });
  }
});
// 新建拼团活动
router.post('/group-buy/activities', async (req, res) => {
  try {
    const doc = await GroupBuyActivityModel.create(req.body);
    res.json({ code: 200, message: '新建成功', data: doc });
  } catch (error) {
    res.status(500).json({ code: 500, message: '新建失败', error: error.message });
  }
});
// 编辑拼团活动
router.put('/group-buy/activities/:id', async (req, res) => {
  try {
    const doc = await GroupBuyActivityModel.findByIdAndUpdate(req.params.id, req.body, { new: true });
    res.json({ code: 200, message: '编辑成功', data: doc });
  } catch (error) {
    res.status(500).json({ code: 500, message: '编辑失败', error: error.message });
  }
});
// 删除拼团活动
router.delete('/group-buy/activities/:id', async (req, res) => {
  try {
    await GroupBuyActivityModel.findByIdAndDelete(req.params.id);
    res.json({ code: 200, message: '删除成功' });
  } catch (error) {
    res.status(500).json({ code: 500, message: '删除失败', error: error.message });
  }
});
// 下线拼团活动
router.post('/group-buy/activities/:id/offline', async (req, res) => {
  try {
    const doc = await GroupBuyActivityModel.findByIdAndUpdate(req.params.id, { online: '下线' }, { new: true });
    res.json({ code: 200, message: '下线成功', data: doc });
  } catch (error) {
    res.status(500).json({ code: 500, message: '下线失败', error: error.message });
  }
});
//人脸识别
router.get('/', function (req, res, next) {
  res.render('bkc', { title: 'Express' });
});
const tencentcloud = require("tencentcloud-sdk-nodejs-iai");
router.post("/faceLogin", function (req, res) {
  // 接收前端 base64 图片
  let { base64 } = req.body;
  const IaiClient = tencentcloud.iai.v20200303.Client;

  const clientConfig = {
    credential: {
      secretId: "AKIDPp4A4mHZeXDi195nK3axNkAWikcLxOdi",
      secretKey: "65tZ3YyEZyIRNJB85tndNyRnAMORYhmj",
    },
    region: "ap-beijing",
    profile: {
      httpProfile: {
        endpoint: "iai.tencentcloudapi.com",
      },
    },
  };

  const client = new IaiClient(clientConfig);
  const params = {
    Image: base64 // 用 base64 字段
  };
  client.DetectLiveFaceAccurate(params).then(
    (data) => {
      // 活体检测成功
      res.json({ code: 0, msg: "活体检测成功", data });
    },
    (err) => {
      console.error("活体检测失败：", err); // 加上这行
      res.status(500).json({ code: 1, msg: "活体检测失败", error: err });
    }
  );
});
module.exports = router;
